﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.Input;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample91
{
    public class TransformSystem : ComponentSystem
    {
        private Camera Camera;
        private static Vector3 Y = new Vector3(0, 1, 0);

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contextManager"></param>
        public TransformSystem()
        {
        }

        public override void Initialization()
        {
            Vector3[] position = new Vector3[]
            {
                new Vector3(0,0,0),
                new Vector3(22,0,0),
                new Vector3(16,0,16),
                new Vector3(0,0,-22),
                new Vector3(-16,0,16),
                new Vector3(-22,0,0),
                new Vector3(-16,0,-16),
                new Vector3(0,0,22),
                new Vector3(16,0,-16)
            };
            ContextManager.Foreach<RectGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                IRenderGroup render = context.GetContextRenderGroup();
                Camera = render.Camera;
            });
            ContextManager.Foreach<TreeGroup>((group, index) =>
            {
                var p = position[index];
                group.Transform.Position = p;
                return group;
            });
        }

        public override void Update(TimeSpan timeSpan)
        {
            var cameraP = Camera.EyePosition;
            ContextManager.Foreach<TreeGroup>((group) =>
            {
                var x = group.Transform.Position.X - cameraP.X;
                var z = group.Transform.Position.Z - cameraP.Z;
                Quaternion quaternion;
                if(z <= 0) quaternion = Quaternion.CreateFromAxisAngle(Y, (float)(Math.Atan(x / z)));
                else quaternion = Quaternion.CreateFromAxisAngle(Y, (float)(Math.PI + Math.Atan(x / z)));
                Context context = ContextManager.GetContext(group.Entity);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateFromQuaternion(quaternion) * Matrix4x4.CreateTranslation(group.Transform.Position);
                context.PushToRenderGroup();
            });
            ContextManager.Foreach<RectGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                context.PushToRenderGroup();
            });
            ContextManager.Foreach<NoneGroup>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                context.PushToRenderGroup();
            });
        }
    }
}
